package com.yjt.fresh.activity;

import android.content.Intent;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.wzgiceman.rxretrofitlibrary.retrofit_rx.http.HttpManager;
import com.wzgiceman.rxretrofitlibrary.retrofit_rx.listener.HttpOnNextListener;
import com.yjt.fresh.R;
import com.yjt.fresh.adpater.AdpRvAtyProducts;
import com.yjt.fresh.api.ApiGetProducts;
import com.yjt.fresh.base.BaseSimpleActivity;
import com.yjt.fresh.bean.BeanProduct;
import com.yjt.fresh.constant.MyConstants;
import com.yjt.fresh.utils.CommonsToolsHelper;
import com.yjt.fresh.utils.PreferenceManager;
import com.yjt.fresh.widget.GridSpacingItemDecoration;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * 商品列表
 *
 * @author mcc
 * @date 2018/6/15
 */

public class AtyProducts extends BaseSimpleActivity {
    @BindView(R.id.rv_app_aty_products)
    RecyclerView mRv;
    @BindView(R.id.rl_app_aty_search_back)
    RelativeLayout mRlBack;
    @BindView(R.id.btn_app_aty_search_search)
    Button mBtnSearch;
    @BindView(R.id.tv_app_aty_products_general)
    TextView mTvGeneral;
    @BindView(R.id.tv_app_aty_products_salesQuantity)
    TextView mTvSalesQuantity;
    @BindView(R.id.tv_app_aty_products_price)
    TextView mTvPrice;
    @BindView(R.id.tv_app_aty_products_distance)
    TextView mTvDistance;
    @BindView(R.id.srlAppAtyProducts)
    SwipeRefreshLayout mRefreshLayout;
    @BindView(R.id.vAppAtyProductsGeneral)
    View mVGeneral;
    @BindView(R.id.rlAppAtyProductsGeneral)
    RelativeLayout mRlGeneral;
    @BindView(R.id.vAppAtyProductsSaleQuantity)
    View mVSaleQuantity;
    @BindView(R.id.rlAppAtyProductsSaleQuantity)
    RelativeLayout mRlSaleQuantity;
    @BindView(R.id.vAppAtyProductsPrice)
    View mVPrice;
    @BindView(R.id.rlAppAtyProductsPrice)
    RelativeLayout mRlPrice;
    @BindView(R.id.vAppAtyProductsDistance)
    View mVDistance;
    @BindView(R.id.rlAppAtyProductsDistance)
    RelativeLayout mRlDistance;
    @BindView(R.id.tvAppAtyProductsSearch)
    TextView mTvSearch;
    @BindView(R.id.rlAppAtyProductsKeyWord)
    RelativeLayout mRlKeyWord;
    @BindView(R.id.tvAppAtyProductsType)
    TextView mTvType;
    @BindView(R.id.ivAppAtyProductsPrice)
    ImageView mIvPrice;
    @BindView(R.id.rlAppAtyProductsSearch)
    RelativeLayout mRlSearch;
    private Map<String, String> mParamMap;
    private int mNextRequestPage = 1;
    private AdpRvAtyProducts mAdpProducts;
    private boolean isLoadMore;
    private boolean priceIsDESC = false;
    private boolean isShowProgress = true;
    private boolean isSortByDistance;
    private String mOrder = "SORT";
    private String mStoreID;


    @Override
    protected int getContentView() {
        return R.layout.app_aty_products;
    }

    @Override
    protected void initViews() {
        ButterKnife.bind(this);
        mStoreID = getIntent().getStringExtra(MyConstants.STORE_ID);
    }

    @Override
    protected void initEvent() {
        initRv();
        initParam();
        getData();
        initRefresh();
        initClick();
    }

    private void initRv() {
        GridLayoutManager layoutManager = new GridLayoutManager(mContext, 2);
        List<BeanProduct> list = new ArrayList<>();
        mRv.setLayoutManager(layoutManager);
        mAdpProducts = new AdpRvAtyProducts(R.layout.app_recycle_item_products, list);
        mRv.addItemDecoration(new GridSpacingItemDecoration(2, CommonsToolsHelper.dip2px(mContext, 5), true));
        mRv.setAdapter(mAdpProducts);
    }

    private void initParam() {
        String searchOrCategory = getIntent().getStringExtra(MyConstants.SEARCH_OR_CATEGORY);
        String keyWord = getIntent().getStringExtra(MyConstants.PRODUCT_KEY_WORD);
        mParamMap = new HashMap<>();
        if (!TextUtils.isEmpty(mStoreID)){
            mParamMap.put("STORE_ID",mStoreID);
        }
        mParamMap.put("currentPage", mNextRequestPage+"");
//        mParamMap.put("CITY", PreferenceManager.getInstance().getCity());
        mParamMap.put("ORDER", "SORT");
        if (MyConstants.SEARCH.equals(searchOrCategory)) {
            mRlKeyWord.setVisibility(View.VISIBLE);
            mTvSearch.setText(keyWord);
            mTvType.setVisibility(View.GONE);
            mParamMap.put("keywords", keyWord);

        } else if (MyConstants.CATEGORY.equals(searchOrCategory)) {
            mRlKeyWord.setVisibility(View.GONE);
            mTvType.setVisibility(View.VISIBLE);
            mRlSearch.setVisibility(View.VISIBLE);
            String firstType = getIntent().getStringExtra(MyConstants.PRODUCT_FIRST_TYPE);
            String secondType = getIntent().getStringExtra(MyConstants.PRODUCT_SECOND_TYPE);
            mParamMap.put("ONE_TYPE", firstType);
            if (!CommonsToolsHelper.isEmty(secondType)) {
                mParamMap.put("TWO_TYPE", secondType);
                mTvType.setText(secondType);
            }else {
                mTvType.setText(firstType);
            }
        }
        mParamMap.put("ORDER", mOrder);
    }

    HttpOnNextListener<List<BeanProduct>> mProductsListener = new HttpOnNextListener<List<BeanProduct>>() {
        @Override
        public void onNext(List<BeanProduct> beanProducts) {
            isShowProgress = true;
            if (isLoadMore) {
                setData(false, beanProducts);
            } else {
                setData(true, beanProducts);
                mRefreshLayout.setRefreshing(false);
            }
        }

        @Override
        public void onReLogin() {
            toLogin();
        }
    };

    private void setData(boolean isRefresh, List<BeanProduct> data) {
        mAdpProducts.setEmptyView(R.layout.view_empty);
        mNextRequestPage++;
        final int size = data == null ? 0 : data.size();
        if (isRefresh) {
            mAdpProducts.setNewData(data);
            mAdpProducts.setEnableLoadMore(true);
            if (isSortByDistance) {
                sortByDistance();
                mRv.scrollToPosition(0);
            }
        } else {
            if (size > 0) {
                mAdpProducts.addData(data);
                mAdpProducts.loadMoreComplete();
            }else {
                mAdpProducts.loadMoreEnd(true);
                mAdpProducts.setEnableLoadMore(false);
            }
            if (isSortByDistance) {
                sortByDistance();
            }
        }

    }

    private void sortByDistance() {
        for (int i = 0; i < mAdpProducts.getData().size(); i++) {
            PreferenceManager manager = PreferenceManager.getInstance();
            BeanProduct beanProduct = mAdpProducts.getData().get(i);
            beanProduct.setLocalLatitude(Double.valueOf(manager.getLatitude()));
            beanProduct.setLocalLongitude(Double.valueOf(manager.getLongitude()));

        }
        Collections.sort(mAdpProducts.getData());
        mAdpProducts.notifyDataSetChanged();
    }

    private void getData() {
        initParam();
        ApiGetProducts apiGetProducts = new ApiGetProducts(mProductsListener, mContext, isShowProgress, false, false);
        apiGetProducts.setMap(mParamMap);
        HttpManager.getInstance().doHttpDeal(apiGetProducts);
    }

    private void initRefresh() {
        mRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                mNextRequestPage = 1;
                isLoadMore = false;
                isShowProgress = false;
                getData();
            }
        });
        mAdpProducts.setOnLoadMoreListener(new BaseQuickAdapter.RequestLoadMoreListener() {
            @Override
            public void onLoadMoreRequested() {
                isLoadMore = true;
                getData();
            }
        }, mRv);
        mAdpProducts.setEmptyView(R.layout.view_empty);
    }

    private void initClick() {
        mRlBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

        mTvSearch.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (TextUtils.isEmpty(mStoreID)) {
                    Intent intent = new Intent(mContext,AtySearch.class);
                    startActivity(intent);
                }else {
                    finish();
                }
            }
        });

        mRlSearch.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(mContext,AtySearch.class);
                startActivity(intent);
            }
        });
        mRlGeneral.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mTvGeneral.setTextColor(getMyColor(R.color.color_43b624));
                mTvDistance.setTextColor(getMyColor(R.color.color_333333));
                mTvPrice.setTextColor(getMyColor(R.color.color_333333));
                mTvSalesQuantity.setTextColor(getMyColor(R.color.color_333333));

                mVGeneral.setVisibility(View.VISIBLE);
                mVSaleQuantity.setVisibility(View.GONE);
                mVPrice.setVisibility(View.GONE);
                mVDistance.setVisibility(View.GONE);
                mOrder = "SORT";
                mNextRequestPage = 1;
                isSortByDistance = false;
                isLoadMore = false;
                mIvPrice.setImageResource(R.mipmap.icon_price_default);
                priceIsDESC = false;
                getData();
            }
        });

        mRlSaleQuantity.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mTvSalesQuantity.setTextColor(getMyColor(R.color.color_43b624));
                mTvDistance.setTextColor(getMyColor(R.color.color_333333));
                mTvPrice.setTextColor(getMyColor(R.color.color_333333));
                mTvGeneral.setTextColor(getMyColor(R.color.color_333333));

                mVSaleQuantity.setVisibility(View.VISIBLE);
                mVGeneral.setVisibility(View.GONE);
                mVPrice.setVisibility(View.GONE);
                mVDistance.setVisibility(View.GONE);
                mNextRequestPage = 1;
                isLoadMore = false;
                isSortByDistance = false;
                mOrder = "GROUP_COUNT_DESC";
                mIvPrice.setImageResource(R.mipmap.icon_price_default);
                priceIsDESC = false;
                getData();
            }
        });

        mRlDistance.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mTvDistance.setTextColor(getMyColor(R.color.color_43b624));
                mTvSalesQuantity.setTextColor(getMyColor(R.color.color_333333));
                mTvPrice.setTextColor(getMyColor(R.color.color_333333));
                mTvGeneral.setTextColor(getMyColor(R.color.color_333333));

                mVDistance.setVisibility(View.VISIBLE);
                mVGeneral.setVisibility(View.GONE);
                mVPrice.setVisibility(View.GONE);
                mVSaleQuantity.setVisibility(View.GONE);
                isSortByDistance = true;
                sortByDistance();
                mIvPrice.setImageResource(R.mipmap.icon_price_default);
                priceIsDESC = false;
            }
        });

        mRlPrice.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                mTvPrice.setTextColor(getMyColor(R.color.color_43b624));
                mTvDistance.setTextColor(getMyColor(R.color.color_333333));
                mTvGeneral.setTextColor(getMyColor(R.color.color_333333));
                mTvSalesQuantity.setTextColor(getMyColor(R.color.color_333333));

                mVPrice.setVisibility(View.VISIBLE);
                mVSaleQuantity.setVisibility(View.GONE);
                mVGeneral.setVisibility(View.GONE);
                mVDistance.setVisibility(View.GONE);
                mNextRequestPage = 1;
                if (priceIsDESC) {
                    mOrder = "DISPLAY_PRICE_DESC";
                    mIvPrice.setImageResource(R.mipmap.b1_ic_j03);
                } else {
                    mOrder = "DISPLAY_PRICE_ASC";
                    mIvPrice.setImageResource(R.mipmap.b1_ic_j02);

                }
                isLoadMore = false;
                isSortByDistance = false;
                priceIsDESC = !priceIsDESC;
                getData();
            }
        });

        mAdpProducts.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                Intent intent = new Intent(mContext, AtyProductDetail.class);
                intent.putExtra(MyConstants.GOODS_ID,mAdpProducts.getItem(position).getGOODS_ID());
                startActivity(intent);
            }
        });
    }

    private int getMyColor(int colorResID) {
        return getResources().getColor(colorResID);
    }

}
